package de.fhaugsburg.games.boardgames.scrabble.terminal;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class Terminal {

	private int id;
	
	public Terminal(int id) {
		this.id = id;
	}
	
	
	/**
	 * returns server message as String
	 * @return
	 */
	private String readMessage() {
		File fTmp = new File(TerminalUtils.SERVER_MSG + this.id);
		if (fTmp.exists()) {
			try {
				// read file
				String sTmp = TerminalUtils.readFile(fTmp);
				// delete file
				fTmp.delete();
				return sTmp;
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	/**
	 * writes message for server
	 * @param sTmp
	 */
	private void writeResponse(String sTmp) {
		File fTmp = new File(TerminalUtils.INPUT_RESPONSE + this.id);
		try {
			TerminalUtils.writeFile(fTmp, sTmp);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * check if server requests input
	 * @return
	 */
	private String checkRequest(){
		
		File fTmp = new File(TerminalUtils.INPUT_REQUEST + this.id);
		
		if (fTmp.exists()) {
			// read file
			String sTmp = "";
			try {
				sTmp = TerminalUtils.readFile(fTmp);
			} catch (IOException e) {
				e.printStackTrace();
			}
			// delete file
			fTmp.delete();
			return sTmp;
		}
		
		return null;
	}
	
	/**
	 * gets single line from input console
	 * @return
	 */
	private String getInput(){
		BufferedReader in = new BufferedReader(new InputStreamReader( System.in ));
		try {
			return in.readLine();
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	
	/**
	 * initialize the terminal
	 * @throws InterruptedException
	 */
	private void run() throws InterruptedException{
		
		//write back request to signal presence of terminal 
		writeResponse(this.id + TerminalUtils.FREE_TERMINAL_SLOT);
		
		//poll for requests
		while (true) {
			// check for new message
			String sTmp = this.readMessage();
			if (sTmp != null) {
				//print to screen
				System.out.println(sTmp);
				System.out.println();
			}
			
			// check for input request from server
			String request = this.checkRequest();
			if (request != null) {
				System.out.print(request);
				//input from console
				this.writeResponse(this.getInput());
			}
			
			// sleep for a while... hush little baby...
			Thread.sleep(100);
		}
	}

	
	
	
	
	/**
	 * tries to get a free terminal slot
	 * @return 0 if no free slot could be obtained
	 */
	private static int getTerminalSlot(){
		File serverDir = new File(TerminalUtils.MSG_DIR);
		File[] tempFiles = serverDir.listFiles();
		for (File tempFile : tempFiles){
			if (tempFile.getAbsolutePath().startsWith(TerminalUtils.INPUT_REQUEST)){
				String request;
				try {
					request = TerminalUtils.readFile(tempFile).trim();
					if (request.endsWith(TerminalUtils.FREE_TERMINAL_SLOT)){
						tempFile.delete();
						return Integer.parseInt(request.substring(0, 1));
					}
				} catch (IOException e) {
					return 0;
				}
			}
		}
		return 0;
	}
	
	
	
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {

		System.out.println("Scrabble Terminal");
		System.out.println("searching for running game...");
		int freeslot = getTerminalSlot();
		if (freeslot != 0){
			System.out.println("connected. Waiting for server to start the game...");
			new Terminal(freeslot).run();
		}else{
			System.err.println("Unable to connect to game. Please start server first.");
		}
	}

}
